using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using DotNet.Utilities.Results.D;
using SqlSugar;
/*
 * 源码己托管: http://gitee.com/dlgcy/dotnetcodes
 * 版本：2024年4月14日
 */
namespace DotNet.Utilities.Sql.SqlSugar
{
    /// <summary>
    /// SqlSugar 帮助类
    /// </summary>
    public class SqlSugarHelper
	{
		#region 成员

		public SqlSugarClient Db { get; private set; }

		private SqlSugarHelper(SqlSugarClient db)
		{
			Db = db;
		}

		/// <summary>
		/// 获取数据库帮助类对象（将会创建数据库）
		/// </summary>
		/// <param name="db"><see cref="SqlSugarClient"/> 对象</param>
		/// <returns>成功返回相应对象，失败返回 null</returns>
		public static SqlSugarHelper GetNewHelper(SqlSugarClient db)
		{
			var helper = new SqlSugarHelper(db);

			bool isCreateDbSuccess = helper.Db.DbMaintenance.CreateDatabase();
			if(!isCreateDbSuccess)
			{
				Console.WriteLine("创建数据库失败!");
				return null;
			}

			return helper;
		}

		#endregion

		#region 增删改查

		/// <summary>
		/// 更新或插入实体列表
		/// </summary>
		/// <param name="rows">列表数据</param>
		public ResultData<List<T>> UpdateOrInsert<T>(List<T> rows) where T : EntityBase, new()
		{
			var data = new List<T>();
			var result = ResultData<List<T>>.SuccessResult(data);

			try
			{
				var collection = Db.Queryable<T>();
				rows.ForEach(entity =>
				{
					if(string.IsNullOrWhiteSpace(entity.Id))
					{
						entity.Id = Guid.NewGuid().ToString();
					}

					T entityInDb = collection.Where(x => x.Id == entity.Id).ToList().FirstOrDefault();
					if(entityInDb == null)
					{
						entity.CreateTime = DateTime.Now;
						entity.UpdateTime = DateTime.Now;
						Db.Insertable(entity).ExecuteCommand();
					}
					else
					{
						entity.CreateTime = entityInDb.CreateTime;
						entity.UpdateTime = DateTime.Now;
						entity.IsDeleted = false;
						Db.Updateable(entity).ExecuteCommand();
					}
				});

				result.Data = data;
			}
			catch(Exception ex)
			{
				result.IsSuccess = false;
				result.Message = $"更新或插入数据时异常：{ex}";
				Console.WriteLine(result.Message);
			}

			return result;
		}

		/// <summary>
		/// 删除实体列表
		/// </summary>
		/// <param name="rows">列表数据</param>
		/// <param name="isSoftDelete">是否软删除</param>
		public ResultMsg Delete<T>(List<T> rows, bool isSoftDelete = true) where T : EntityBase, new()
		{
			var result = ResultMsg.SuccessMsg();
			try
			{
				var collection = Db.Queryable<T>();

				//如果不是软删除，可批量删除;
				if(!isSoftDelete)
				{
					//var ids = rows.Select(x => x.Id).ToList();
					//int count = Db.Deleteable<T>(x => ids.Contains(x.Id)).ExecuteCommand();
					int count = Db.Deleteable(rows).ExecuteCommand();
					if(count != rows.Count)
					{
						result.IsSuccess = false;
						result.Message = $"仅删除了 {rows.Count} 条记录中的 {count} 条";
					}

					return result;
				}

				rows.ForEach(entity =>
				{
					T entityInDb = collection.Where(x => x.Id == entity.Id).ToList().FirstOrDefault();
					if(entityInDb == null)
					{
						//Ignore
					}
					else
					{
						entity.IsDeleted = true;
						entity.UpdateTime = DateTime.Now;
						Db.Updateable(entity).ExecuteCommand();
					}
				});
			}
			catch(Exception ex)
			{
				result.IsSuccess = false;
				result.Message = $"删除数据时异常：{ex}";
				Console.WriteLine(result.Message);
			}

			return result;
		}

		/// <summary>
		/// 删除实体列表
		/// </summary>
		/// <param name="idList">ID列表</param>
		/// <param name="isSoftDelete">是否软删除</param>
		public void DeleteByIds<T>(List<string> idList, bool isSoftDelete = true) where T : EntityBase, new()
		{
			var deleteList = Find<T>(x => idList.Contains(x.Id)).ToList();
			Delete<T>(deleteList, isSoftDelete);
		}

		/// <summary>
		/// 查找实体列表
		/// </summary>
		/// <param name="predicate">条件</param>
		/// <returns>实体列表</returns>
		public ISugarQueryable<T> Find<T>(Expression<Func<T, bool>> predicate = null) where T : EntityBase, new()
		{
			var collection = Db.Queryable<T>();
			var datas = collection.Where(x => x.IsDeleted == false);
			if(predicate != null)
			{
				datas = datas.Where(predicate);
			}

			return datas;
		}

		#endregion
	}
}
